package com.wolfalpha.utron.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.update.UmengDownloadListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormalActivity;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.app.AppManager;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.FileUtils;
import com.wolfalpha.utron.view.AlertDialog;

import java.io.File;

/**
 * 设置列表界面
 *
 * @author lodon
 */
public class SettingActivity extends BaseNormalActivity implements OnClickListener {

    private RelativeLayout rlMessage;       //消息设置
    private RelativeLayout rlFeedback;      //反馈
    private RelativeLayout rlAgreement;     //用户协议
    private RelativeLayout rlAbout;         //关于优创会
    private RelativeLayout rlCheckUpdate;   //检查更新
    private RelativeLayout rlClearCache;    //清理缓存

    private Button btnLogout;               //退出账号

    private TextView tvVersion;             //版本号
    private TextView tvCache;               //缓存大小

    private final static int GO_MESSAGE = 1;
    private final static int GO_FEEDBACK = 2;
    private final static int GO_AGREEMENT = 3;
    private final static int GO_ABOUT = 4;
    private final static int GO_UPDATE = 5;
    private final static int GO_CLEAR = 6;
    private final static int GO_LOGOUT = 7;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GO_MESSAGE:
                    //进入消息设置界面
                    UIHelper.showActivity(SettingActivity.this, SettingMessageActivity.class);
                    break;
                case GO_FEEDBACK:
                    //进入反馈界面
                    UIHelper.showActivity(SettingActivity.this, FeedBackActivity.class);
                    break;
                case GO_AGREEMENT:
                    //进入用户协议界面
                    UIHelper.showActivity(SettingActivity.this, AgreementActivity.class);
                    break;
                case GO_ABOUT:
                    //进入关于优创会界面
                    UIHelper.showActivity(SettingActivity.this, AboutActivity.class);
                    break;
                case GO_LOGOUT:
                    //退出当前账号
                    AppContext.getInstance().logout();
                    AppContext.getInstance().removeProperty(new String[]{"utron_account", "utron_pwd", "logined"});
                    AppManager.getAppManager().finishOActivity();
                    UIHelper.showActivityAndFinish(SettingActivity.this, LoginActivity.class);
                    break;
                case GO_UPDATE:
                    //检查更新
                    if (hasNewVersion) {
                        final AlertDialog ad = new AlertDialog(SettingActivity.this);
                        ad.setTitle("应用更新");
                        ad.setMessage("确认现在更新?");
                        ad.setNegativeButton("取消", new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ad.dismiss();
                            }
                        });
                        ad.setPositiveButton("确认", new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (response != null) {
                                    if (UmengUpdateAgent.downloadedFile(SettingActivity.this, response) == null)
                                        UmengUpdateAgent.startDownload(SettingActivity.this, response);
                                }
                                ad.dismiss();
                            }
                        });
                    }
                    break;
                case GO_CLEAR:
                    //清理缓存
                    if (initCache() == null) {
                        UIHelper.ToastMessage(SettingActivity.this, "没有缓存");
                        break;
                    }
                    UIHelper.clearAppCache(SettingActivity.this);
                    UIHelper.ToastMessage(SettingActivity.this, "清理成功");
                    tvCache.setText(initCache());
                    break;
            }
        }
    };

    private boolean hasNewVersion = false;
    private UpdateResponse response = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        initView();
        initListeners();

        UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
            @Override
            public void onUpdateReturned(int updateStatus, final UpdateResponse updateInfo) {
                switch (updateStatus) {
                    case UpdateStatus.Yes: // has update
                        final String version = updateInfo.version;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                response = updateInfo;
                                hasNewVersion = true;
                                tvVersion.setText("有新版本:v" + version);
                            }
                        });
                        break;
                    case UpdateStatus.No: // has no update
//                        Toast.makeText(SettingActivity.this, "没有更新", Toast.LENGTH_SHORT).show();
                        break;
                    case UpdateStatus.NoneWifi: // none wifi
//                        Toast.makeText(SettingActivity.this, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
                        break;
                    case UpdateStatus.Timeout: // time out
                        Toast.makeText(SettingActivity.this, "超时", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
        UmengUpdateAgent.update(SettingActivity.this);
        UmengUpdateAgent.setUpdateUIStyle(UpdateStatus.STYLE_NOTIFICATION);

        UmengUpdateAgent.setDownloadListener(new UmengDownloadListener() {
            @Override
            public void OnDownloadStart() {

            }

            @Override
            public void OnDownloadUpdate(int i) {

            }

            @Override
            public void OnDownloadEnd(int i, String s) {
                UmengUpdateAgent.startInstall(SettingActivity.this, UmengUpdateAgent.downloadedFile(SettingActivity.this, response));
            }
        });
    }

    /**
     * 初始化界面
     */
    private void initView() {
        setTvTitle("设置");

        rlMessage = (RelativeLayout) findViewById(R.id.ly_setting_message);
        rlFeedback = (RelativeLayout) findViewById(R.id.ly_setting_feefback);
        rlAgreement = (RelativeLayout) findViewById(R.id.ly_setting_agreement);
        rlAbout = (RelativeLayout) findViewById(R.id.ly_setting_about);
        rlCheckUpdate = (RelativeLayout) findViewById(R.id.ly_setting_check_update);
        rlClearCache = (RelativeLayout) findViewById(R.id.ly_setting_clear_cache);

        tvVersion = (TextView) findViewById(R.id.tv_setting_version);
        tvCache = (TextView) findViewById(R.id.tv_setting_cache);
        btnLogout = (Button) findViewById(R.id.btn_setting_logout);

        tvCache.setText(initCache());
    }

    /**
     * 初始化监听
     */
    private void initListeners() {
        rlMessage.setOnClickListener(this);
        rlFeedback.setOnClickListener(this);
        rlAgreement.setOnClickListener(this);
        rlAbout.setOnClickListener(this);
        rlCheckUpdate.setOnClickListener(this);
        rlClearCache.setOnClickListener(this);
        btnLogout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_setting_message:
                handler.sendEmptyMessage(GO_MESSAGE);
                break;
            case R.id.ly_setting_feefback:
                handler.sendEmptyMessage(GO_FEEDBACK);
                break;
            case R.id.ly_setting_agreement:
                handler.sendEmptyMessage(GO_AGREEMENT);
                break;
            case R.id.ly_setting_about:
                handler.sendEmptyMessage(GO_ABOUT);
                break;
            case R.id.ly_setting_check_update:
                handler.sendEmptyMessage(GO_UPDATE);
                break;
            case R.id.ly_setting_clear_cache:
                handler.sendEmptyMessage(GO_CLEAR);
                break;
            case R.id.btn_setting_logout:
                handler.sendEmptyMessage(GO_LOGOUT);
                break;
        }
    }


    /**
     * 获取缓存大小
     */
    private String initCache() {
        // 璁＄畻缂撳瓨澶у皬
        long fileSize = 0;
        String cacheSize = "0KB";
        File filesDir = getFilesDir();
        File cacheDir = getCacheDir();

//        fileSize += FileUtils.getDirSize(filesDir);
        fileSize += FileUtils.getDirSize(cacheDir);
        // 2.2鐗堟湰鎵嶆湁灏嗗簲鐢ㄧ紦瀛樿浆绉诲埌sd鍗＄殑鍔熻兘
        if (AppContext.isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
            try {
                File externalCacheDir = this.getExternalCacheDir();

                fileSize += FileUtils.getDirSize(externalCacheDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (fileSize > 0)
            cacheSize = FileUtils.formatFileSize(fileSize);

        return cacheSize;
    }

}
